﻿using System;
using System.Text;
using System.Windows.Forms;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace COB.SharePoint.Utilities.DeploymentWizard.UI
{
    /// <summary>
    /// Browser form to select site collection
    /// 
    /// Created: 2009-12-19, Perry Rapp
    /// Edited:  2009-12-27, Perry Rapp
    /// </summary>
    public partial class frmSiteCollectionBrowse : Form
    {
        private Guid m_webAppId;
        private string m_siteCollectionUrl;
        private int m_nErrors = 0;

        // Properties
        // caller can set these for initial display
        // caller checks these after form closes to see user's choices
        public Guid SelectedWebAppId { get { return m_webAppId; } set { m_webAppId = value; } }
        public string SelectedSiteCollectionUrl { get { return m_siteCollectionUrl; } set { m_siteCollectionUrl = value; } }
        
        /// <summary>
        /// Constructor
        /// </summary>
        public frmSiteCollectionBrowse()
        {
            InitializeComponent();
        }

        // Methods
        private void frmSiteCollectionBrowse_Load(object sender, EventArgs e)
        {
            CenterToParent();

            try
            {
                DisplayWebApplications(SPFarm.Local);
            }
            catch (Exception exc)
            {
                DisplayError("Listing Web Applications", exc);
            }
        }

        /// <summary>
        /// Load and display the list of web applications on the farm
        /// </summary>
        /// <param name="farm"></param>
        private void DisplayWebApplications(SPFarm farm)
        {
            // Clear site collections, as it is a cascade display from this list
            ClearSiteCollectionsList();

            // Set up columns
            lstWebApplications.Columns.Clear();
            lstWebApplications.Columns.Add("Name", 250);
            lstWebApplications.Columns.Add("# Site Coll.", 75);

            // Loop through and display all web applications (including CentralAdmin)
            SPWebService webService = farm.Services.GetValue<SPWebService>("");
            foreach (SPWebApplication webApp in webService.WebApplications)
            {
                ListViewItem item = new ListViewItem();
                item.Text = (webApp.DisplayName.Length > 0 ? webApp.DisplayName : webApp.Name);
                item.SubItems.Add(webApp.Sites.Count.ToString());
                item.Tag = webApp.Id;
                lstWebApplications.Items.Add(item);
                if (webApp.Id == m_webAppId)
                {
                    item.Selected = true;
                }
            }
        }

        private void lstWebApplications_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearSiteCollectionsList();
            if (lstWebApplications.SelectedItems.Count > 0)
            {
                string guidString = lstWebApplications.SelectedItems[0].Tag.ToString();
                m_webAppId = new Guid(guidString);

                try
                {
                    Cursor.Current = Cursors.WaitCursor;

                    DisplaySiteCollections(SPFarm.Local);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        private void DisplaySiteCollections(SPFarm farm)
        {
            ClearSiteCollectionsList();

            // Set up columns
            lstSiteCollections.Columns.Clear();
            lstSiteCollections.Columns.Add("Name", 150);
            lstSiteCollections.Columns.Add("# Webs", 75);
            lstSiteCollections.Columns.Add("URL", 100);

            // Open requested web application and
            // Loop through and display all site collections on it
            SPWebService webService = farm.Services.GetValue<SPWebService>("");
            SPWebApplication webApp = webService.WebApplications[m_webAppId];
            foreach (SPSite site in webApp.Sites)
            {
                string siteUrl = "?";
                try
                {
                    siteUrl = site.Url; // in case of exception
                    ListViewItem item = new ListViewItem();
                    item.Text = site.RootWeb.Title;
                    item.SubItems.Add(site.AllWebs.Count.ToString());
                    item.SubItems.Add(site.Url);
                    item.Tag = site.Url;
                    if (site.Url == m_siteCollectionUrl)
                    {
                        item.Selected = true;
                    }
                    lstSiteCollections.Items.Add(item);
                }
                catch (Exception exc)
                {
                    DisplayError("Exception listing site collection: " + siteUrl, exc);
                }
                finally
                {
                    site.Dispose();
                }
            }
        }

        private void ClearSiteCollectionsList()
        {
            lstSiteCollections.Items.Clear();
        }

        private void lstSiteCollections_Click(object sender, EventArgs e)
        {
            if (lstSiteCollections.SelectedItems.Count > 0)
            {
                m_siteCollectionUrl = lstSiteCollections.SelectedItems[0].SubItems[2].Text;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }

        }
        private void DisplayError(string status, Exception exc)
        {
            if (status.Length > 0 && !status.EndsWith(":"))
            {
                status += ":";
            }
            OutputLine(status);
            OutputLine("\t" + exc.Message);
            ++m_nErrors;
            grpErrors.Text = string.Format("Errors ({0})", m_nErrors);
            grpErrors.Enabled = true;
        }
        private void OutputLine(string text)
        {
            TextBoxUtil.AppendLineAndScroll(txtErrors, text);
        }
    }
}
